package retrofit.boot.annotation;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.util.Assert;
import retrofit.boot.util.RetrofitUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wulg on 2019/11/11
 * description:
 */
public final class RetrofitClientsRegistrationBean extends RetrofitClientRegistrySupport implements BeanDefinitionRegistryPostProcessor {

    private List<RetrofitClientWrapper> wrapperList;

    public RetrofitClientsRegistrationBean(RetrofitClientWrapper.Builder... builders) {
        Assert.isTrue(ArrayUtils.isNotEmpty(builders),"RetrofitClientWrapper.Builder must be configured");
        wrapperList = new ArrayList<>();
        for(RetrofitClientWrapper.Builder builder : builders){
            wrapperList.add(builder.build());
        }
    }

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        for(RetrofitClientWrapper wrapper : wrapperList){
            wrapper.setName(resolve(wrapper.getName()));
            wrapper.setUrl(RetrofitUtils.rebuildUrl(wrapper.getUrl()));
            registerRetrofitClients(beanDefinitionRegistry,wrapper);
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {
        //
    }
}
